from datetime import datetime
#from urllib import request

from flask import Flask, redirect, url_for, render_template,request
from flask_sqlalchemy import SQLAlchemy

import config

app = Flask(__name__)
app.config.from_object(config.Dbconfig)
db = SQLAlchemy(app)


class Book(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    publish_office = db.Column(db.String(100), nullable=False)
    ISSN = db.Column(db.String(100), nullable=False)
    storage_time = db.Column(db.DateTime, default=datetime.now)


def __init__(self, title, publisher, issn):
    self.title = title
    self.publish_office = publisher
    self.ISSN = issn


db.create_all()


@app.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        bookname = request.form['bookname']
        publisher = request.form['publisher']
        issn = request.form['issn']
        print(bookname, publisher, issn)
        book1 = Book(title=bookname,publisher=publisher,issn=issn)
        db.session.add(book1)
        db.session.commit()
        return redirect(url_for('index'))
    else:
        return render_template('add.html')


@app.route('/')
def index():
    books = Book.query.all()
    return render_template('index.html', bookset=books)

@app.route('/find',methods=['GET','POST'])
def find():
    if request.method =='POST':
        issn=request.form['issn']
        books=Book.query.filter_by(ISSN=issn).all()
        if books==[]:
            return redirect('/')
        else:
            return render_template('index.html',bookset=books)
    else:
        return redirect('/')
if __name__ == '__main__':
    app.run(debug=True)
